package com.squirrel.michale;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/2/23 9:35 PM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class LeetCode0274 {

    public int hIndex(int[] citations) {
        Arrays.sort(citations);
        int h = 0, i = citations.length - 1;
        while (i >= 0 && citations[i] > h) {
            h++;
            i--;
        }
        return h;
    }

    public int hIndex2(int[] citations) {
        int n = citations.length, tot = 0;
        int[] counter = new int[n + 1];
        for (int i = 0; i < n; i++) {
            if (citations[i] >= n) {
                counter[n]++;
            } else {
                counter[citations[i]]++;
            }
        }
        for (int i = n; i >= 0; i--) {
            tot += counter[i];
            if (tot >= i) {
                return i;
            }
        }
        return 0;
    }


    public int hIndex2Lite(int[] citations) {
        int n = citations.length, tot = 0;
        int[] counter = new int[n + 1];
        for (int i = 0; i < n; i++) {
            if (citations[i] >= n) {
                counter[n]++;
            } else {
                counter[citations[i]]++;
            }
        }
        for (int i = n; i >= 0; i--) {
            tot += counter[i];
            if (tot >= i) {
                return i;
            }
        }
        return 0;
    }

//    作者：力扣官方题解
//    链接：https://leetcode.cn/problems/h-index/solutions/869042/h-zhi-shu-by-leetcode-solution-fnhl/
//    来源：力扣（LeetCode）
//    著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

    public int hIndex3(int[] citations) {
        int hIndex = 0;
        Integer[] copy = new Integer[citations.length];
        for (int i = 0; i < citations.length; i++) {
            copy[i] = citations[i];
        }
        Arrays.sort(copy, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });

        for (int i = 0; i < copy.length; i++) {
            if (copy[i] <= i+1) {
                hIndex = copy[i];
                break;
            }
        }
        return hIndex;
    }

    public static void main(String[] args) {
        LeetCode0274 leetCode0274 = new LeetCode0274();
        int[] citations = new int[]{3, 0, 6, 1, 5};
//        System.out.println(leetCode0274.hIndex(citations));
        System.out.println(leetCode0274.hIndex2(citations));

        int[] citation2 = new int[]{3,1,1};
//        System.out.println(leetCode0274.hIndex(citation2));
        System.out.println(leetCode0274.hIndex2(citation2));


        int[] citation3 = new int[]{100};
//        System.out.println(leetCode0274.hIndex(citation3));
        System.out.println(leetCode0274.hIndex2(citation3));

    }
}
